var net = require('net');
var HOST = '127.0.0.1';
//var HOST = '192.168.0.103';
var DeviceStatusDAO = require('./model/DeviceStatus');
var PORT = 7000;
if(typeof MsgType == "undefined"){
  var MsgType = {} ;
  MsgType.MSG_REGISTOR = 0 ;
  MsgType.MSG_MONTTOR = 1;
  MsgType.MSG_RETURN = 2;
}
if(typeof RetCode == "undefined"){
  var RetCode = {} ;
  RetCode.SUCC = 1 ;
  RetCode.ERR = 0;
}
TcpServer = function(_manager){
  this.manager = _manager ;
  
};
var manager = null ;
TcpServer.prototype.setmanager= function(_manager){
  manager = _manager;
};
function ProcessRegistor(sock,msg){
  
  var registorInfo = JSON.parse(msg);
  console.log("Registe Date:"+registorInfo.date) ;

  console.log("DevName:"+registorInfo.sensorInfo.strDevName+" DevNo"+ registorInfo.sensorInfo.iDevNo) ;
  var result = {} ;
  result.iRet = RetCode.SUCC ;
  result.strDescrip = "succ" ;
  if(sock.writable){
	try{
		sock.write(JSON.stringify(result));
	}catch(err){
		console.log(err);
	}
  }
}
function ProcessMsg(sock,msg){
  //console.log(msg);
  var msgObj = JSON.parse(msg) ;
  //console.log(msg) ;
  switch(msgObj.type){
    case MsgType.MSG_REGISTOR:
      ProcessRegistor(sock,msgObj.content) ;
      break ;
    default:
      //console.log(msg) ;
      manager.uiServer.monitorEvent.emit("MonitorUpdate",msg);
      //DeviceStatusDAO.findByIdAndUpdate(JSON.parse(msgObj.content),null);
      var content = JSON.parse(msgObj.content);
      DeviceStatusDAO.findByIdAndUpdate(content,function(err,obj){
        //console.log(err);
      });
      
      break ;
  }
}
function Client(){
  this.socket = null ;
  this.msg = [];
  this.brokenmsg = "";

}
Client.prototype.IsCompleteMsg = function(str){
	var regular1 = /^{(.*)}$/ ;
	var regular2 = /}{/ ;
	if(regular2.test(str)){//it is combined joint msg
		if(regular1.test(str)){ //joint complete msg
			//console.log(str+ "===is joint complete msg") ;
/*			var tmp = regular2.exec(str);
			tmp.forEach(function(subTmp){
				//console.log(subTmp);
			});*/
			return 2; 
		}else {//it is broken msg and complete msg combination
			//console.log(str+ "=== broken and complete msg combination");
			return 3;
		}
	}else{//it is not jointmsg
		if(regular1.test(str)){
			//console.log(str+"===complete msg and no joint");
			return 0 ;
		}else {//it is broken msg
			console.log(str+" ===broken msg and no joint");
			return 1 ;
		}
	}

};
Client.prototype.MsgFunc = function(strMsg){
    strMsg = this.brokenmsg + strMsg ;
    //console.log("before split:"+strMsg);
    var combinationStatus = this.IsCompleteMsg(strMsg);
    switch(combinationStatus){
      case 0: 
        //console.log(strMsg) ;
        this.msg[0] = strMsg ;
        ProcessMsg(this.socket,this.msg[0]);
        break ;
      case 1: 
        //console.log(strMsg) ;
        this.msg = [];
        this.brokenmsg = strMsg;
        break ;
      case 2:
        strMsg = strMsg.substring(1,strMsg.length-1);
        this.msg = strMsg.split('}{') ;
        this.msg.forEach(function(subMsg){
          //console.log('sub:{'+subMsg+'}');
          ProcessMsg(this.socket,'{'+subMsg+'}');
          ///console.log('{'+subMsg+'}');
        });
        break ;
      case 3:
        strMsg = strMsg.substring(1) ;
        this.msg = strMsg.split('}{') ;
        this.brokenmsg = this.msg.pop();
        this.msg.forEach(function(subMsg){
          //console.log('{'+subMsg+'}');
          ProcessMsg(this.socket,'{'+subMsg+'}');
        });
          //console.log(this.brokenmsg);
        break ;
        
    }
    /*
    this.msg = strMsg.split('}{') ;
    var last_msg = this.msg[this.msg.length-1];
    var first_msg = this.msg[0];
    if(last_msg.charAt(last_msg.length-1)!='}'){
      this.brokenmsg = this.msg.pop() ;
      this.brokenmsg = '{'+this.brokenmsg ;
    }
    //this.brokenmsg = 
    first_msg = first_msg.substring(1);
    this.msg[0] = first_msg ;
    this.msg.forEach(function(subMsg){
      console.log('{'+subMsg+'}');
    });*/
};
var clients = [] ;
/*
function Result() {
this.iRet = 0 ;
this.strDescrip = "" ;
};*/

/*
exports.start = function(){
  net.createServer(function(sock) {
    console.log('CONNECTED: ' +
          sock.remoteAddress + ':' + sock.remotePort);
    var client = new Client() ;
    client.socket = sock ;
    clients.push(client) ;
    sock.on('data', function(data) {
      clients.forEach(function(sockClient){
      //console.log(sockClient);
      var msg = data.toString() ;
        if(sockClient.socket == sock){
          console.log("content:"+msg) ;
          sockClient.MsgFunc(msg);
          console.log('============================');
        }
      });
      //
      //console.log('DATA ' + sock.remoteAddress + ': ' + data);
      //ProcessMsg(sock,msg);
    });
    sock.on('close', function(data) {
      console.log('CLOSED: ' + sock.remoteAddress + ' ' + sock.remotePort);
    });
  }).listen(PORT, HOST);
  console.log('Server listening on ' + HOST +':'+ PORT);
};*/

TcpServer.prototype.start = function(){
  net.createServer(function(sock) {
    console.log('CONNECTED: ' +
          sock.remoteAddress + ':' + sock.remotePort);
    var client = new Client() ;
    client.socket = sock ;
    clients.push(client) ;
    sock.on('data', function(data) {
      clients.forEach(function(sockClient){
      //console.log(sockClient);
      var msg = data.toString() ;
        if(sockClient.socket == sock){
          //console.log("content:"+msg) ;
          sockClient.MsgFunc(msg);
          //console.log('============================');
          //console.log(TcpServer);
          
         
        }
      });
      //
      //console.log('DATA ' + sock.remoteAddress + ': ' + data);
      //ProcessMsg(sock,msg);
    });
    sock.on('close', function(data) {
      console.log('CLOSED: ' + sock.remoteAddress + ' ' + sock.remotePort);
    });
	sock.on('error',function(err){
		console.log(err);
	});
  }).listen(PORT, HOST);
  console.log('Server listening on ' + HOST +':'+ PORT);
};
module.exports = TcpServer ;